package ru.osu.acm.testing.beans;

import ru.osu.acm.common.entities.Group;
import ru.osu.acm.common.entities.Person;
import ru.osu.acm.common.config.Config;
import ru.osu.acm.common.industrial.PersonFactory;
import ru.osu.acm.testing.Utils;

import javax.annotation.Resource;
import javax.faces.model.SelectItem;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.faces.application.FacesMessage;
import javax.faces.validator.ValidatorException;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Date;
import java.sql.*;

/**
 * User: Integra
 * Date: 10.07.2009
 * Time: 17:55:34
 */
public class RegisterTeamBean {
    @Resource(name = Config.jndi)
    private DataSource source;

    private int personCount;
    private int selectedPerson1;
    private int selectedPerson2;
    private int selectedPerson3;
    private ArrayList<SelectItem> selectPerson;
    private ArrayList<Person> allPerson = new ArrayList<Person>();

    public int getSelectedPerson2() {
        return selectedPerson2;
    }

    public void setSelectedPerson2(int selectedPerson2) {
        this.selectedPerson2 = selectedPerson2;
    }

    public int getSelectedPerson3() {
        return selectedPerson3;
    }

    public void setSelectedPerson3(int selectedPerson3) {
        this.selectedPerson3 = selectedPerson3;
    }

    public int getPersonCount() {
        getPersons();
        return allPerson.size();
    }

    public void setPersonCount(int personCount) {
        this.personCount = personCount;
    }

    public int getSelectedPerson1() {
        return selectedPerson1;
    }

    public void setSelectedPerson1(int selectedPerson1) {
        this.selectedPerson1 = selectedPerson1;
    }

    public ArrayList<SelectItem> getSelectPerson() {
        if (selectPerson == null) {
            selectPerson = new ArrayList<SelectItem>();
            getPersons();
        }
        return selectPerson;
    }

    public void setSelectPerson(ArrayList<SelectItem> selectPerson) {
        selectPerson = selectPerson;
    }


    public String addTeamToDB() {
        boolean ok = true;
        String login = Utils.getRequestParam("formregisterTeam:login");
        String password = Utils.getRequestParam("formregisterTeam:password");
        String confirmpassword = Utils.getRequestParam("formregisterTeam:confirmpassword");
        String name = Utils.getRequestParam("formregisterTeam:teamname");
        int id = 1;
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select * from team order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    id = resultSet.getInt("id") + 1;
                    if (resultSet.getString("login").equals(login)) {
                        ok = false;
                        break;
                    }
                }
                resultSet.close();
                statement.close();
                if (ok) {
                    statement = conn.prepareStatement("insert into team(id, login, pass, teamname) values ( ?, ?, ?, ?)");
                    statement.setInt(1, id);
                    statement.setString(2, login);
                    statement.setString(3, password);
                    statement.setString(4, name);
                    statement.executeUpdate();
                    statement.close();

                    //add members
                    int id_personteam = 1;
                    statement = conn.prepareStatement("select teamperson.id from teamperson order by id");
                    resultSet = statement.executeQuery();
                    while (resultSet.next()) {
                        id_personteam = resultSet.getInt("id") + 1;
                    }
                    statement.close();
                    resultSet.close();
                    if (selectedPerson1 != -1) {
                        statement = conn.prepareStatement("insert into teamperson(id, team, person,startdate,stopdate) values (?,?,?,?,?)");
                        statement.setInt(1, id_personteam);
                        statement.setInt(2, id);
                        statement.setInt(3, selectedPerson1);
                        statement.setDate(4, new java.sql.Date(new Date().getTime()));
                        statement.setDate(5, null);
                        statement.executeUpdate();
                        statement.close();
                        id_personteam += 1;
                    }
                    if (selectedPerson2 != -1) {
                        statement = conn.prepareStatement("insert into teamperson(id, team, person,startdate,stopdate) values (?,?,?,?,?)");
                        statement.setInt(1, id_personteam);
                        statement.setInt(2, id);
                        statement.setInt(3, selectedPerson2);
                        statement.setDate(4, new java.sql.Date(new Date().getTime()));
                        statement.setDate(5, null);
                        statement.executeUpdate();
                        statement.close();
                        id_personteam += 1;
                    }
                    if (selectedPerson3 != -1) {
                        statement = conn.prepareStatement("insert into teamperson(id, team, person,startdate,stopdate) values (?,?,?,?,?)");
                        statement.setInt(1, id_personteam);
                        statement.setInt(2, id);
                        statement.setInt(3, selectedPerson3);
                        statement.setDate(4, new java.sql.Date(new Date().getTime()));
                        statement.setDate(5, null);
                        statement.executeUpdate();
                        statement.close();
                    }
                }

            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        if (ok) {
            return "login";
        } else {
            return "registerTeam";
        }
    }

    public void passValidator(FacesContext context, UIComponent component, Object value) {
        String pass = Utils.getRequestParam("formregisterTeam:password");
        String curpass = value.toString();
        if (curpass.length() < 5) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setDetail(Utils.getLocaleMessage("minLengthOfPassword"));
            message.setSummary(Utils.getLocaleMessage("minLengthOfPassword"));
            throw new ValidatorException(message);
        }
        if (!pass.equals(curpass)) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setDetail(Utils.getLocaleMessage("notEquilsPassword"));
            message.setSummary(Utils.getLocaleMessage("notEquilsPassword"));
            throw new ValidatorException(message);
        }
    }

    public void loginValidator(FacesContext context, UIComponent component, Object value) {

        String detail = Utils.getLocaleMessage("existLogin");
        String summary = Utils.getLocaleMessage("existLogin");
        boolean ok = true;
        if (value == null) return;
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select * from team order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    if (resultSet.getString("login").equals(value.toString())) {
                        ok = false;
                        break;
                    }
                }
                resultSet.close();
                statement.close();
                if (!ok) {
                    FacesMessage message = new FacesMessage();
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    message.setDetail(detail);
                    message.setSummary(summary);
                    throw new ValidatorException(message);
                }

            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void teamNameValidator(FacesContext context, UIComponent component, Object value) {

        // TODO: add correct messages!
        String detail = "This name of the team already exists";
        String summary = "This name of the team already exists";
        boolean ok = true;
        if (value == null) return;
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select * from team order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    if (value.toString().equals(resultSet.getString("teamname"))) {
                        ok = false;
                        break;
                    }
                }
                resultSet.close();
                statement.close();
                if (!ok) {
                    FacesMessage message = new FacesMessage();
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    message.setDetail(detail);
                    message.setSummary(summary);
                    throw new ValidatorException(message);
                }

            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void getPersons() {
        allPerson = loadPerson();
        selectPerson.clear();
        selectPerson.add(new SelectItem(-1, "none"));
        selectedPerson1 = -1;
        selectedPerson2 = -1;
        selectedPerson3 = -1;
        for (Person g : allPerson) {
            if (g.getId() != 4)
                selectPerson.add(new SelectItem(g.getId(), g.getName() + " " + g.getSurname() + " ( " + g.getUsername() + " )"));
        }
    }

    public ArrayList<Person> loadPerson() {
        return PersonFactory.getAllPersons(Utils.getConnection(source), true);
    }
}